package com.haier.npt.user;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolverComposite;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.haier.npt.common.JsonResult;
import com.haier.npt.filter.TokenUtil;
import com.haier.npt.sso.client.UserClient;
import com.haier.npt.sso.domain.HaierUser;
import com.haier.npt.utils.JsonUtils;

public class UserHandlerMethodArgumentResolver extends HandlerMethodArgumentResolverComposite{

	@Autowired
	private UserClient userClient;
	
	@Override
	public boolean supportsParameter(MethodParameter parameter){
		Class<?> classzz = parameter.getParameterType();
		if(classzz.isAssignableFrom(HaierUser.class) || classzz.isAssignableFrom(Long.class)){
			return parameter.hasParameterAnnotation(CurrentUser.class);
		}
		return false;
	}
	
	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
    NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
		//获取token
		String token = TokenUtil.getRequestAccessToken(request);
		if(StringUtils.isEmpty(token)){
			throw new MissingServletRequestParameterException("access_token", parameter.getNestedParameterType().getSimpleName());
		}
		else{
			JsonResult<Object> result = this.userClient.getUserInfo(token);
			if(result.getCode()==0){
				Map<String,Object> userObject = (Map)result.getData();
				if(userObject.containsKey("password")){
					String userJson = JsonUtils.mapToString(userObject);
					HaierUser currentUser = JsonUtils.toBean(userJson,HaierUser.class);
					Class<?> classzz = parameter.getParameterType();
                    /**
                     * 对象类型返回 对象
                     */
					if(classzz.isAssignableFrom(HaierUser.class)){
						return currentUser;
					}
					
                    /**
                     * long 返回当前登录人id
                     */
                    if (classzz.isAssignableFrom(Long.class)) {
                        return currentUser.getId();
                    }
				}
			}
			return new RemoteAccessException("UserClint Remote call failed", result.getThrowable());
		}
	}
}
